package com.nic.view.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nic.view.R;
import com.nic.view.model.CommonChooseBean;
import com.nic.view.widget.CalendarViewDialog;
import com.nic.view.widget.CustomDatePicker;
import com.nic.view.widget.ToolBarHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import permission.PermissionActivity;


/**
 * Created by Administrator on 2018/11/2.
 */

public abstract class VBaseActivity extends PermissionActivity {

    public Context mContext;
    public boolean isForeground;
    private boolean isBack = true;
    private ToolBarHelper toolBarHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = this;
        setStatusBarColor(R.color.title_color);//4.4手机状态栏设置
        setContentView(getContentLayoutId());
        initPreviewData();
        initView();
        initViewData();
//        registerDictionaryListener();

    }


    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        if (layoutResID == 0) {
            return;
        }
        toolBarHelper = new ToolBarHelper();
        toolBarHelper.setContentView(this, layoutResID);
        setSupportActionBar(toolBarHelper.getToolbar());
        setToolbarInit();
        super.setContentView(toolBarHelper.getRootLayout());
    }

    private void setStatusBarColor(int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ViewGroup firstChildAtDecorView = ((ViewGroup) ((ViewGroup) getWindow().getDecorView()).getChildAt(0));
            View statusView = new View(this);
            ViewGroup.LayoutParams statusViewLp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight());
            //颜色的设置可抽取出来让子类实现之
            statusView.setBackgroundColor(ContextCompat.getColor(this, colorId));
            firstChildAtDecorView.addView(statusView, 0, statusViewLp);

            ViewGroup contentFrameLayout = (ViewGroup) findViewById(android.R.id.content);
            View parentView = contentFrameLayout.getChildAt(0);
            if (parentView != null) {
                parentView.setFitsSystemWindows(true);
            }

        }
    }

    /**
     * @param activity
     * @param useThemestatusBarColor   是否要状态栏的颜色，不设置则为透明色
     * @param withoutUseStatusBarColor 是否不需要使用状态栏为暗色调
     */
    public void setStatusBar(Activity activity, boolean useThemestatusBarColor, boolean withoutUseStatusBarColor, int barColorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = activity.getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            if (useThemestatusBarColor) {
                activity.getWindow().setStatusBarColor(ContextCompat.getColor(activity, barColorId));
            } else {
                activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = activity.getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !withoutUseStatusBarColor) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    private int getStatusBarHeight() {
        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            return getResources().getDimensionPixelSize(resId);
        }
        return 0;
    }

    /**
     * 设置statusbar颜色
     *
     * @param activity
     * @param dark
     */
    public void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    public void setTheme(Activity activity, boolean dark, int barColorId, int toolbarBgColorId) {
        setStatusBar(this, true, false, barColorId);
        setAndroidNativeLightStatusBar(activity, dark);
        getToolbar().setBackgroundColor(ContextCompat.getColor(activity, toolbarBgColorId));

    }

    private void setToolbarInit() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//显示返回图标
        getSupportActionBar().setHomeButtonEnabled(true);//主键按钮能否可点击
//        toolBarHelper.getToolbar().setNavigationIcon(R.mipmap.ic_back);
        toolBarHelper.getToolbar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isBack) {
                    finish();
                }

            }
        });
    }

    @Override
    public void setContentView(View view) {
        toolBarHelper.setContentView(this, view);
        setSupportActionBar(toolBarHelper.getToolbar());
        setToolbarInit();
        super.setContentView(toolBarHelper.getRootLayout());
    }

    public void setToolbarTitle(String title) {
        toolBarHelper.setToolbarTitle(title);
    }

    public void setToolbarVisibility(int visible) {
        toolBarHelper.setToolbarVisibility(visible);
    }

    public TextView getToolbarRightTv() {

        return toolBarHelper.getTvRight();
    }

    public ImageView getToolbarRightIv() {

        return toolBarHelper.getIvRight();
    }

    public ImageView getToolbarRightIv2() {
        return toolBarHelper.getIvRight2();
    }

    public TextView getToolbarTitleTv() {

        return toolBarHelper.getTvTitle();
    }

    /**
     * @param resId         返回图标
     * @param clickListener
     */
    public void setOnBackListener(int resId, View.OnClickListener clickListener) {
        isBack = false;
        if (resId != 0) {
            toolBarHelper.getToolbar().setNavigationIcon(resId);
        }
        toolBarHelper.getToolbar().setNavigationOnClickListener(clickListener);
    }

    public Toolbar getToolbar() {
        return toolBarHelper.getToolbar();
    }

    public abstract int getContentLayoutId();

    public void initPreviewData() {
    }

    ;//前

    public abstract void initView();//中

    public void initViewData() {
    }

    ;//后

    public void showToastSHORT(String title) {
        Toast.makeText(this, title, Toast.LENGTH_SHORT).show();
    }

    public void registerDictionaryListener() {
        IntentFilter intentFilter = new IntentFilter(SingleChooseActivity.ACTION_SEND);
        registerReceiver(receiverDictionary, intentFilter);
    }

    public void unRegisterDictionaryListener() {
        unregisterReceiver(receiverDictionary);
    }

    private BroadcastReceiver receiverDictionary = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SingleChooseActivity.ACTION_SEND)) {
                CommonChooseBean commonChooseBean = (CommonChooseBean) intent.getSerializableExtra("item");
                String tag = intent.getStringExtra("tag");
                if (onSingleDictionaryListener != null) {
                    onSingleDictionaryListener.onItemClick(tag, commonChooseBean);
                }
            }
        }
    };
    private OnSingleDictionaryListener onSingleDictionaryListener;

    public void setOnSingleDictionaryListener(OnSingleDictionaryListener onSingleDictionaryListener) {
        this.onSingleDictionaryListener = onSingleDictionaryListener;
    }

    /**
     * 字典条目点击监听
     */
    public interface OnSingleDictionaryListener {
        void onItemClick(String tag, CommonChooseBean item);
    }

    /**
     * 日期
     *
     * @param editText
     */
    public void showCustomerDatePopWindow(final TextView editText, CustomDatePickerType datePickerType) {
        showCustomerDatePopWindow(editText, datePickerType, false);
    }

    /**
     * 日期
     *
     * @param editText
     */
    public void showCustomerDatePopWindow(final TextView editText, final CustomDatePickerType datePickerType, final boolean isShowHourAndMinute) {
        try {
            final String pattern = "yyyy-MM-dd HH:mm";
            final String pattern1 = "yyyy-MM-dd";
            final String pattern2 = "yyyy-MM-dd HH:mm:ss";
            String selectedDate = editText.getText().toString();
            if (TextUtils.isEmpty(selectedDate)) {
                if (isShowHourAndMinute) {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.CHINA);
                    selectedDate = sdf.format(new Date());
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern1, Locale.CHINA);
                    selectedDate = sdf.format(new Date());
                }

            }

            CustomDatePicker datePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
                @Override
                public void handle(String time) {
                    if (datePickerType != CustomDatePickerType.ALL) {
                        try {
                            Date selectDateTime = new SimpleDateFormat(pattern).parse(time);
                            Calendar selectC = Calendar.getInstance();
                            selectC.setTime(selectDateTime);
                            int selectYear = selectC.get(Calendar.YEAR);
                            int selectMonth = selectC.get(Calendar.MONTH);
                            int selectDay = selectC.get(Calendar.DAY_OF_MONTH);
                            int selectHour = selectC.get(Calendar.HOUR_OF_DAY);
                            int selectMinute = selectC.get(Calendar.MINUTE);
                            Calendar c = Calendar.getInstance();
                            int year = c.get(Calendar.YEAR);
                            int month = c.get(Calendar.MONTH);
                            int day = c.get(Calendar.DAY_OF_MONTH);
                            int hour = c.get(Calendar.HOUR_OF_DAY);
                            int minute = c.get(Calendar.MINUTE);
                            if (datePickerType == CustomDatePickerType.FUTURE) {
                                if (selectYear < year) {
                                    showToastSHORT("不能低于当前年，请重新选择");
                                    return;
                                }
                                if (selectYear == year && selectMonth < month) {
                                    showToastSHORT("不能低于当月份，请重新选择");
                                    return;
                                }
                                if (selectYear == year && selectMonth == month && selectDay < day) {
                                    showToastSHORT("不能低于当日期，请重新选择");
                                    return;
                                }
                                if (isShowHourAndMinute) {
                                    if (selectYear == year && selectMonth == month && selectDay == day && selectHour < hour) {
                                        showToastSHORT("不能低于当时间，请重新选择");
                                        return;
                                    }
                                    if (selectYear == year && selectMonth == month && selectDay == day && selectHour == hour && selectMinute < minute) {
                                        showToastSHORT("不能低于当时间，请重新选择");
                                        return;
                                    }
                                }
                            }
                            if (datePickerType == CustomDatePickerType.HISTORY) {
                                if (selectYear > year) {
                                    showToastSHORT("不能超出当前年，请重新选择");
                                    return;
                                }
                                if (selectYear == year && selectMonth > month) {
                                    showToastSHORT("不能超出当月份，请重新选择");
                                    return;
                                }
                                if (selectYear == year && selectMonth == month && selectDay > day) {
                                    showToastSHORT("不能超出当日期，请重新选择");
                                    return;
                                }
                                if (isShowHourAndMinute) {
                                    if (selectYear == year && selectMonth == month && selectDay == day && selectHour > hour) {
                                        showToastSHORT("不能超出当时间，请重新选择");
                                        return;
                                    }
                                    if (selectYear == year && selectMonth == month && selectDay == day && selectHour == hour && selectMinute > minute) {
                                        showToastSHORT("不能超出当时间，请重新选择");
                                        return;
                                    }
                                }
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    if (isShowHourAndMinute) {
                        editText.setText(time);
                    } else {
                        editText.setText(time.split(" ")[0]);
                    }

                }
            });
            datePicker.showSpecificTime(isShowHourAndMinute);
            datePicker.show(selectedDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public enum CustomDatePickerType {
        HISTORY,
        FUTURE,
        ALL
    }

    /**
     * 日期
     *
     * @param context
     * @param editText
     */
    public void showDatePopWindow(Context context, final TextView editText, final boolean isHistory) {
        try {
            final CalendarViewDialog mCalendarViewDialog = new CalendarViewDialog(context, CalendarViewDialog.CORRECT_TO_DAY_1ST);
            mCalendarViewDialog.setOnBtnClickListener(new CalendarViewDialog.OnBtnClickListener() {
                @Override
                public void onClick(View v) {
                    String selectTime = mCalendarViewDialog.getCalendarDate("yyyy-MM-dd");
                    if (isHistory) {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            if (!new Date().after(format.parse(selectTime))) {
                                showToastSHORT("不能大于当前时间，请重新选择");
                                return;
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    editText.setText(selectTime);
                }
            });
            mCalendarViewDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showDatePopWindow(final TextView editText, final boolean isHistory) {
        showDatePopWindow(this, editText, isHistory);
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isForeground = isAppOnForeground();
    }

    @Override
    protected void onDestroy() {
//        unRegisterDictionaryListener();
//        toolBarHelper = null;
        super.onDestroy();
    }

    /**
     * @param listener    权限通过监听
     * @param resId       权限描述string Id
     * @param permissions 权限
     */
    public void checkAppPermission(CheckPermListener listener, int resId, String... permissions) {
        checkPermission(listener, resId, permissions);
    }

}
